package com.kelp.codetoolkit.ui.form

import com.intellij.openapi.project.Project
import com.intellij.ui.components.JBList
import com.kelp.codetoolkit.data.SpringConfigListItem
import com.kelp.codetoolkit.renderer.SpringConfigListCellRenderer
import java.awt.BorderLayout
import java.awt.Component
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*

/**
 * @author: liuyuebai
 * @date: 2025/9/11 15:44
 * @description:
 */
class SpringConfigItemPanel(private val project: Project, private val item: Any) : JPanel(BorderLayout())  {

    init {
        when (item) {
            is Map<*, *> -> {
                val list = JBList(item.keys.toList())
                list.cellRenderer = object : DefaultListCellRenderer() {
                    override fun getListCellRendererComponent(
                        list: JList<out Any>?,
                        value: Any?,
                        index: Int,
                        isSelected: Boolean,
                        cellHasFocus: Boolean
                    ): Component {
                        val component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
                        return component
                    }
                }
                add(JScrollPane(list), BorderLayout.CENTER)

                list.addMouseListener(object : MouseAdapter() {
                    override fun mouseClicked(e: MouseEvent?) {
                        val selectedKey = list.selectedValue as String
                        val selectedItem = item[selectedKey]
                        if (selectedItem != null) {
                            val subPanel = SpringConfigItemPanel(project, selectedItem)
                            add(subPanel, BorderLayout.SOUTH)
                            revalidate()
                            repaint()
                        }
                    }
                })
            }

            is List<*> -> {
                val list = JBList(item)
                add(JScrollPane(list), BorderLayout.CENTER)
                list.addMouseListener(object : MouseAdapter() {
                    override fun mouseClicked(e: MouseEvent?) {
                        val selectedItem = list.selectedValue
                        if (selectedItem != null) {
                            val subPanel = SpringConfigItemPanel(project, selectedItem)
                            add(subPanel, BorderLayout.SOUTH)
                            revalidate()
                            repaint()
                        }
                    }
                })
            }

            else -> {
                add(JTextField(item.toString()), BorderLayout.CENTER)
            }
        }
    }
}